package category

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"
	"strings"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetCategoryListApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetCategoryListApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetCategoryListApiLogic {
	hostname, _ := os.Hostname()
	return &GetCategoryListApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetCategoryListApiLogic) GetCategoryListApi() (resp []types.CategoryListResp, err error) {
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	categoryEntities, err := dao.CategoryEntity.WithContext(l.ctx).Where(
		dao.CategoryEntity.EnterpriseID.Eq(enterpriseId),
	).Order(dao.CategoryEntity.Sort, dao.CategoryEntity.ID.Desc()).Find()
	if err != nil {
		return make([]types.CategoryListResp, 0), nil
	}
	categoryListResps := k.Map(categoryEntities, func(item *model.CategoryEntity, index int) types.CategoryListResp {
		return types.CategoryListResp{
			ID:       item.ID,       // 主键id
			Name:     item.Name,     //分类名称
			ParentID: item.ParentID, // 父节点id
			Sort:     item.Sort,     // 排序
		}
	})
	return categoryListResps, nil
}

func (l *GetCategoryListApiLogic) GetCategoryNameApi(categoryIdList []int64) (string, error) {
	categoryEntities, err := dao.CategoryEntity.WithContext(l.ctx).Where(dao.CategoryEntity.ID.In(categoryIdList...)).Find()
	if err != nil {
		return "", err
	}
	categoryMap := k.ToMap(categoryEntities, func(item *model.CategoryEntity) (int64, string) {
		return item.ID, item.Name
	})
	var resultName = make([]string, 0)
	for _, item := range categoryIdList {
		resultName = append(resultName, categoryMap[item])
	}
	return strings.Join(resultName, "/"), nil
}
